//
//  LZLFindRecommendViewModel.swift
//  swiftDemo
//
//  Created by luozhilin on 2018/9/18.
//  Copyright © 2018年 luozhilin. All rights reserved.
//

import UIKit
import SwiftyJSON
import HandyJSON

class RecommendViewModel: NSObject {
    var findRecommendModel:FindRecommendModel?
    var streamList:[FindRStreamList]?
    
    typealias AddDataBlock = () ->Void
    var updateBlock:AddDataBlock?
    
}

// 模拟请求数据
extension RecommendViewModel{
    
    func refreshDataSource(){
        
        let filePath = Bundle.main.path(forResource: "FindRecommend", ofType: "json")
        let jsonData = NSData(contentsOfFile: filePath!)
        
        // 对应拿到json就要进行解析
        let json = JSON(jsonData!)
        
        if let mappedObject = JSONDeserializer<FindRecommendModel>.deserializeFrom(json: json["data"].description) {
            self.findRecommendModel = mappedObject
            self.streamList = mappedObject.streamList
            self.updateBlock?()
        }
    }
}


// MARK 数据源
extension RecommendViewModel{
    
    // 一共展示多少item
    func numberOfRowsInSection(section:NSInteger) -> NSInteger{
        
        return self.streamList?.count ?? 0
    }
    
    // 每一个item的高度计算
    func heightForRowAtIndexPath(indexPath:NSIndexPath) -> CGFloat{
        
        let picNum = self.streamList?[indexPath.row].picUrls?.count ?? 0
        var num:CGFloat = 0
        
        if picNum>0 && picNum<=3 {
            num = 1
        }else if picNum>3 && picNum<=6{
            num = 2
        }else if picNum>6 && picNum<=9{
            num = 3
        }
        
        // 显示的图片都是正方形的
        let onePictureHeight = CGFloat((YYScreenWidth-30)/3)
        
        return 60+50+onePictureHeight*num+calculateTextHeight(for: self.streamList?[indexPath.row])
    }
    
    func calculateTextHeight(for commentText:FindRStreamList?) -> CGFloat{
        
        var height:CGFloat = 44
        guard let model = commentText else {
            return height
        }
        
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 15)
        label.numberOfLines = 0
        label.text = model.content
        
        height+=label.sizeThatFits(CGSize(width: YYScreenWidth-30, height: CGFloat.infinity)).height+10
        
        return height
    }
}










































